package com.jacky.cglib;

import com.jacky.jdk.BookApi;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: jacky
 * @date: 2018/6/4
 * Time: 11:44
 * Description:
 **/
public class CglibDynamicProxy {
    public BookApi createCglibDynamicProxy() throws Exception {

        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(new CglibInterceptor());
        enhancer.setInterfaces(new Class[]{BookApi.class});
        BookApi cglibProxy = (BookApi) enhancer.create();
        return cglibProxy;
    }

    public class CglibInterceptor implements MethodInterceptor {
        @Override
        public Object intercept(Object object, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            //添加代理逻辑
            if (method.getName().equals("sell")) {
                System.out.print("");
            }
            return null;
        }
    }
}
